package com.whzykj.ctrl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.whzykj.common.DateUtil;
import com.whzykj.common.DbUtil;
import com.whzykj.model.Account;
import com.whzykj.model.Customer;
import com.whzykj.model.Userinfo;

public class CustomerController extends Controller{
	public void index(){
		this.renderJsp("/admin/system/customerList.jsp");
	}
	
	/*
	 * 列表显示所有客户信息
	 */
	public void listCustomer(){
		Integer page = this.getParaToInt("page");
		Integer rows = this.getParaToInt("rows");
		StringBuffer condition=new StringBuffer(" where 1=1 ");
		Integer station=this.getParaToInt("station");
		if(station!=null && station!=-1){
			condition.append(" and cust.STATION_ID="+station);
		}
		String custname=this.getPara("custname");
		if(custname!=null && custname.trim().length()!=0){
			condition.append(" and cust.CUST_NAME like '%"+custname+"%'");
		}
		String mobile=this.getPara("mobile");
		if(mobile!=null && mobile.trim().length()!=0){
			condition.append(" and cust.MOBILE like '%"+mobile+"%'");
		}
		String state=this.getPara("state");
		if(state!=null && !state.trim().equals("-1")){
			if(state.trim().equals("03")){
				condition.append(" and acct.state is NULL");
			}else{
				condition.append(" and acct.state='"+state+"'");
			}
		}
		String sqlBefore = "select cust.*,sta.STATION_NAME,sta1.STATION_NAME as TAKE_STATION,ui.USERNAME,ui1.INIT_PASS,acct.acct_id,acct.state  ";
		StringBuffer sqlAfter = new StringBuffer(
				"from customer cust ");
		sqlAfter.append(" inner join station sta ON cust.STATION_ID=sta.STATION_ID ");
		sqlAfter.append(" inner join station sta1 ON cust.TAKE_STATION_ID=sta1.STATION_ID ");
		sqlAfter.append(" left JOIN userinfo ui on cust.SALESMAN=ui.USERID ");
		sqlAfter.append(" left JOIN userinfo ui1 on cust.CUST_ID=ui1.CUST_ID ");
		sqlAfter.append(" LEFT JOIN account acct on acct.cust_id=cust.CUST_ID");
		sqlAfter.append(condition.toString());
		sqlAfter.append(" order by cust.CREATE_TIME DESC ");
		Page<Customer> paginate = Customer.dao.paginate(page, rows, sqlBefore,
				sqlAfter.toString());
		Map map = new HashMap();
		map.put("rows", paginate.getList());
		map.put("total", paginate.getTotalRow());
		this.renderJson(map);
	}
	
	/**
	 * 进入到添加新客户的页面
	 */
	public void addBefore(){
		Integer stationid=this.getParaToInt(0);
		if(stationid!=null){
			this.setAttr("stationid", stationid);
		}
		this.renderJsp("/admin/system/customerAdd.jsp");
	}
	
	/**
	 * 添加新的客户
	 */
	public void addCustomer(){
		UploadFile upFile=getFile("img", "customer/");
		Object user=this.getSessionAttr("LOGIN_USER");
		if(user==null){
			this.redirect("/login.jsp");
			return;
		}
		Integer userid=((Userinfo)user).getInt("USERID");
		Customer customer=this.getModel(Customer.class);
		boolean res=Customer.dao.findExistsCustomer(customer.getStr("MOBILE"));
		if(res){
			this.setAttr("addMsg", "对不起，您输入的客户电话号码已经存在，添加失败！");
			this.renderJsp("/admin/system/customerAdd.jsp");
			return;
		}
		if(upFile!=null){
			String fileName=upFile.getFileName();
			String imgUrl=PropKit.use("config.properties").get("web.url")+"/upload/customer/"+fileName;
			customer.set("IDENTITY_URL", imgUrl);
		}
		customer.set("CREATE_TIME", DateUtil.getNow());
		customer.set("CREATE_PERSON", userid);
		if(customer.getStr("MARKET_ADDRESS")==null || customer.getStr("MARKET_ADDRESS").equals("")){
			customer.set("MARKET_ADDRESS", "湖北武汉");
		}
		boolean add=customer.save();
		this.setAttr("addMsg", add?"客户信息添加成功！":"客户信息添加失败！");
		this.renderJsp("/admin/system/customerAdd.jsp");
	}
	
	/**
	 * 进入修改客户信息的页面
	 */
	public void editBefore(){
		int cust_id=this.getParaToInt(0);
		Customer customer=Customer.dao.findById(cust_id);
		this.setAttr("customer", customer);
		this.renderJsp("/admin/system/customerEdit.jsp");
	}
	
	/**
	 * 保存修改后的客户信息
	 */
	public void editCustomer(){
		UploadFile upFile=getFile("img", "customer/");	
		//	文件重命名这样用：    getFile().getFile().renameTo(new File(newFileNameHere)); 
		Customer customer=this.getModel(Customer.class);
		if(upFile!=null){
			String fileName=upFile.getFileName();
			String imgUrl=PropKit.use("config.properties").get("web.url")+"/upload/customer/"+fileName;		
			customer.set("IDENTITY_URL", imgUrl);
			
		}
		boolean add=customer.update();
		boolean update=false;
		try {
			if(add){
				Userinfo userinfo=Userinfo.dao.findFirst("SELECT * from userinfo where CUST_ID=?",customer.getInt("CUST_ID"));
				if(userinfo!=null){
					userinfo.set("USERNAME", customer.getStr("CUST_NAME"));
					userinfo.set("MOBILE", customer.getStr("MOBILE"));
					update=userinfo.update();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		this.setAttr("addMsg", (add&&update)?"客户信息修改成功！":"客户信息修改失败");
		this.renderJsp("/admin/system/customerList.jsp");
	}
	
	/**
	 * 更新客户有效状态
	 */
	public void changeValid(){
		Integer custid=this.getParaToInt("custid");
		Integer valid=this.getParaToInt("valid");
		Customer customer=Customer.dao.findById(custid);
		customer.set("IS_VALID", valid);
		boolean update=customer.update();
		Userinfo userinfo=Userinfo.dao.findFirst("select * FROM userinfo where CUST_ID="+custid);
		if(userinfo!=null){
			userinfo.set("ENABLE", valid);
			userinfo.update();
		}
		this.renderText(update?"1":"0");
	}
	
	/**
	 * 客户重置密码
	 */
	public void resetPass(){
		Integer custid=this.getParaToInt("custid");
		String password=this.getPara("password");
		String res=null;	// 	0:重置失败；	1：重置成功；	2：客户还未创建登录信息
		Userinfo userinfo=Userinfo.dao.findFirst("select * FROM userinfo where CUST_ID="+custid);
		if(userinfo!=null){
			userinfo.set("PASSWORD", HashKit.md5(password));
			userinfo.set("INIT_PASS", password);
			boolean update=userinfo.update();
			res=update?"1":"0";
		}else{
			res="2";
		}
		userinfo=null;
		this.renderText(res);
	}
	
	/**
	 * 为客户分配登录账号
	 */
	public void manage(){
		Object user=this.getSessionAttr("LOGIN_USER");
		if(user==null){
			this.redirect("/login.jsp");
			return;
		}
		int userid=((Userinfo)user).getInt("USERID");
		Integer custid=this.getParaToInt("custid");
		String password=this.getPara("password");
		String res=null;	// 	0:账户分配失败；	1：账户分配成功；	2：客户还未创建登录信息
		Userinfo userinfo=Userinfo.dao.findFirst("select * FROM userinfo where CUST_ID="+custid);
		if(userinfo==null){
			userinfo=new Userinfo();
			userinfo.set("PASSWORD", HashKit.md5(password));
			userinfo.set("INIT_PASS", password);
			userinfo.set("USERNAME", this.getPara("custname"));
			userinfo.set("SEX", this.getParaToInt("custsex"));
			userinfo.set("MOBILE", this.getPara("mobile"));
			userinfo.set("CUST_ID", custid);
			userinfo.set("ENABLE", 1);
			userinfo.set("IS_CANCEL", 0);
			userinfo.set("ROLE", 5);
			userinfo.set("CREATE_TIME", DateUtil.getNow());
			boolean add=userinfo.save();
			boolean result=false;
			Account acct=Account.dao.findFirst("select * from account where cust_id=?", custid);
			if(acct!=null){
				this.renderText("0");
				return;
			}else{
				String incSql="SELECT Auto_increment FROM information_schema.tables WHERE Table_Schema='bcytest' AND table_name='account'";
				Record rec=Db.findFirst(incSql);
				int nid=0;
				try {
					nid = rec.getBigInteger("Auto_increment").intValue();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String account_type=this.getPara("account_type");
				List<String> sqlList=new ArrayList<String>();
		//		sqlList.add("DELETE from account where cust_id="+custid);
				StringBuffer sql=new StringBuffer("insert into account(cust_id,account_type,amount,property,state,create_time,last_update_time,last_update_person)");
				sql.append("VALUES("+custid+",'00',0,'00','00','"+DateUtil.getNow()+"','"+DateUtil.getNow()+"',"+userid+")");
				sqlList.add(sql.toString());
				
				sql=new StringBuffer("insert into account_oper(acct_id,oper_type,create_time,operator,remarks)");
				sql.append("VALUES("+nid+",'00','"+DateUtil.getNow()+"',"+userid+",'为客户分配登录账号时自动开户')");
				sqlList.add(sql.toString());				
				try{
					result=DbUtil.batch(sqlList);
				}catch(Exception ex){
					ex.printStackTrace();
					result=false;
				}
			}
			res=(add&&result)?"1":"0";
		}else{
			res="2";
		}
		userinfo=null;
		this.renderText(res);
	}
	
	/**
	 * 根据输入的电话号码，判断客户是否存在
	 */
	public void findExistsCustomer(){
		String mobile=this.getPara("mobile");
		boolean res=Customer.dao.findExistsCustomer(mobile);
		this.renderText(res?"1":"0");
	}
	
	/**
	 * 根据账户ID改变账户状态
	 * @param acct_id
	 * @param status
	 */
	public void changeAccountStatus(){
		Object user=this.getSessionAttr("LOGIN_USER");
		if(user==null){
			this.redirect("/login.jsp");
			return;
		}
		int userid=((Userinfo)user).getInt("USERID");
		int acct_id=this.getParaToInt("acct_id");
		String state=this.getPara("state");
		String fstate="";
		if(state.equals("01")){
			fstate="01";
		}else if(state.equals("02")){
			fstate="02";
		}else if(state.equals("03") || state.equals("04")){
			fstate="00";
		}
		List<String> sqlList=new ArrayList<String>();
		sqlList.add("UPDATE account set state='"+fstate+"' where acct_id="+acct_id);
		
		StringBuffer sql=new StringBuffer("insert into account_oper(acct_id,oper_type,create_time,operator,remarks)");
		sql.append("VALUES("+acct_id+",'"+state+"','"+DateUtil.getNow()+"',"+userid+",'管理员更改客户账户状态')");
		sqlList.add(sql.toString());
		boolean res=false;
		try{
//			int[] cnts=Db.batch(sqlList, 10);
			res=DbUtil.batch(sqlList);
		}catch(Exception ex){
			ex.printStackTrace();
			res=false;
		}
		this.renderText(res?"1":"0");
	}
	
	/**
	 * 为客户开户
	 */
	public void addAccount(){
		Object user=this.getSessionAttr("LOGIN_USER");
		if(user==null){
			this.redirect("/login.jsp");
			return;
		}
		int userid=((Userinfo)user).getInt("USERID");
		int cust_id=this.getParaToInt("cust_id");
		Account acct=Account.dao.findFirst("select * from account where cust_id=?", cust_id);
		if(acct!=null){
			this.renderText("0");
			return;
		}else{
			String incSql="SELECT Auto_increment FROM information_schema.tables WHERE Table_Schema='bcytest' AND table_name='account'";
			Record rec=Db.findFirst(incSql);
			int nid=0;
			try {
				nid = rec.getBigInteger("Auto_increment").intValue();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String account_type=this.getPara("account_type");
			List<String> sqlList=new ArrayList<String>();
			StringBuffer sql=new StringBuffer("insert into account(cust_id,account_type,amount,property,state,create_time,last_update_time,last_update_person)");
			sql.append("VALUES("+cust_id+",'"+account_type+"',0,'"+this.getPara("property")+"','00','"+DateUtil.getNow()+"','"+DateUtil.getNow()+"',"+userid+")");
			sqlList.add(sql.toString());
			
			sql=new StringBuffer("insert into account_oper(acct_id,oper_type,create_time,operator,remarks)");
			sql.append("VALUES("+nid+",'00','"+DateUtil.getNow()+"',"+userid+",'管理员为客户开通账户')");
			sqlList.add(sql.toString());
			boolean res=false;
			try{
				res=DbUtil.batch(sqlList);
			}catch(Exception ex){
				ex.printStackTrace();
				res=false;
			}
			this.renderText(res?"1":"0");
		}
	}
	
}
